#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QDebug>
#include <QTimer>
#include <QTime>
#include <QMessageBox>
#include <QtCharts/QChartView>
#include <QtCharts/QSplineSeries>
#include <QtCharts/QValueAxis>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //初始化页面设置
    ui->setupUi(this);
    Chart_Init();
    ui->radioButton->setEnabled(false);
    ui->pushButton_6->setEnabled(false);
    ui->comboBox_5->setCurrentIndex(3);
    connect(serial,&QSerialPort::readyRead,this,&MainWindow::dataReceive);

    //新建一个QTimer对象
    timer = new QTimer();
    //信号和槽
    connect(timer, SIGNAL(timeout()), this, SLOT(TimerOut()));

    /*定时发送定时器*/
    timersend = new QTimer();
    //connect(ui->checkBox_4,SIGNAL(stateChanged(int)),this,SLOT(TimeSendReady()));
    connect(timersend,SIGNAL(timeout()),this,SLOT(on_pushButton_3_clicked()));

    //接收到信号就开始绘图
    x=0;
    connect(this,&MainWindow::drawsignal,this,&MainWindow::DrawLine);
//    connect(this,&MainWindow::plotsignal, this, SLOT(DrawLine()));

    /*定时器*/
//    timerDrawLine = new QTimer();
//    timerDrawLine->start(100);
//    connect(timerDrawLine, SIGNAL(timeout()), this, SLOT(DrawLine()));

    // 绑定HEX发送chexkBox信号与对应的槽函数
    connect(ui->checkBox_3,SIGNAL(on_pushButton_6_toggled()),this,SLOT(SendDataHex()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    ui->comboBox->clear();
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())     //类似for循环，扫描每一个串口
    {
        QSerialPort _com;
        _com.setPort(info);
        if(_com.open(QIODevice::ReadWrite))
        {
            ui->comboBox->addItem(info.portName());
            _com.close();
        }
    }
}

void MainWindow::on_pushButton_2_clicked()
{
    if(!serial->isOpen())
    {
        serialSet();
        serial->open(QIODevice::ReadWrite);
        ui->radioButton->setChecked(true);
        ui->pushButton_6->setEnabled(true);
        ui->pushButton_2->setText("关闭串口");
    }
    else
    {
        serial->close();
        ui->radioButton->setChecked(false);
        ui->pushButton_2->setText("打开串口");
    }
}

void MainWindow::serialSet()
{   //串口名、速率
    serial->setPortName(ui->comboBox->currentText());
    serial->setBaudRate(ui->comboBox_2->currentText().toLong());
    //comboBox_4是停止位
    switch(ui->comboBox_4->currentIndex())
    {
        case 0:
            serial->setStopBits(QSerialPort::OneStop);
        break;
        case 1:
            serial->setStopBits(QSerialPort::OneAndHalfStop);
        break;
        case 2:
            serial->setStopBits(QSerialPort::TwoStop);
        break;
    }
    //comboBox_5是数据位
    switch(ui->comboBox_5->currentIndex())
    {
        case 0:
            serial->setDataBits(QSerialPort::Data5);
        break;
        case 1:
            serial->setDataBits(QSerialPort::Data6);
        break;
        case 2:
            serial->setDataBits(QSerialPort::Data7);
        break;
        case 3:
            serial->setDataBits(QSerialPort::Data8);
        break;
    }
    //comboBox_3是校验位
    switch(ui->comboBox_3->currentIndex())
    {
        case 0:
            serial->setParity(QSerialPort::NoParity);
        break;
        case 1:
            serial->setParity(QSerialPort::OddParity);
        break;
        case 2:
            serial->setParity(QSerialPort::EvenParity);
        break;
    }
}
//发送窗口的清除文件
void MainWindow::on_pushButton_4_clicked()
{
    ui->textEdit->clear();
    lineSeries->removePoints(-1, x+1);
    x=0;
}
//发送按钮
void MainWindow::on_pushButton_3_clicked()
{
    if(!serial->isOpen())
    {
        qDebug()<<"Not Open";
    }
    else
    {
        QString str = ui->textEdit->toPlainText();
        QStringList list = str.split("\n");
        for(int i = 0; i<list.size(); i++)
        {
            if (list[i] =="")
                continue;
            list[i] += "\r\n";
            serial->write(list[i].toLocal8Bit());
        }
        this->TimeSendReady();
    }
}

void MainWindow::dataReceive()
{
    qDebug()<<"receive";
    QByteArray buffer = serial->readAll();
    //QString string = "";
    //string += tr(buffer);
    QString string;
    //HEX或者ASCII
    if(ui->checkBox->isChecked())
    {
        string = buffer.toHex(' ').trimmed().toUpper();/*hex显示*/
        string.append(" ");
    }
    else
    {
        string = QString(buffer);   /*ascii显示*/
    }
    data=string;
    DrawLine();
    //显示时间戳
    if(ui->checkBox_2->isChecked())
    {
         ui->textBrowser->moveCursor(QTextCursor::End);
         if(ui->checkBox->isChecked())
         {  // 在string末尾添加换行符,十六进制的
             string.append("\n");
         }
         string = QString("[%1]:RX--> %2").arg(QTime::currentTime().toString("HH:mm:ss:zzz")).arg(string);
         ui->textBrowser->insertPlainText(string);
         ui->textBrowser->moveCursor(QTextCursor::End);
    }
    else
    {
        ui->textBrowser->moveCursor(QTextCursor::End);
        ui->textBrowser->insertPlainText(string);
        ui->textBrowser->moveCursor(QTextCursor::End);
    }


}

void MainWindow::on_pushButton_5_clicked()
{
    ui->textBrowser->clear();
    QVector<QPointF> points ;//清空然后replace
    lineSeries->replace(points); //利用replace函数更新数据
    x=0;

}

void MainWindow::SendDataHex()
{
    //获取发送框字符
    SendTextStr = ui->textEdit->document()->toPlainText();
    SendTextByte = SendTextStr.toUtf8();
    if (SendTextStr.isEmpty())
    {
        return;
    }
    //asccii与hex转换
    if (ui->checkBox_3->isChecked())
    {
        //转换成16进制数并转换为大写
        SendTextByte = SendTextByte.toHex(' ').toUpper();
        ui->textEdit->document()->setPlainText(SendTextByte);
    }
    else
    {
        //从QByteArray转换为QString
        SendTextStr = SendTextByte.fromHex(SendTextByte);
        ui->textEdit->document()->setPlainText(SendTextStr);
    }
}

void MainWindow::TimeSendReady()
{
    int settime;
    /*判断定时发送勾选状态*/
    if (ui->checkBox_4->isChecked())
    {
        /*获取设定时间*/
        settime = ui->lineEdit->text().toInt();
        if (settime > 0)
        {
            timersend->start(settime);
        }
        else
        {
            QMessageBox::warning(this, "警告", "时间必须大于0");
        }
         ui->lineEdit->setEnabled(false);
    }
    else
    {
        /*停止发送*/
        timersend->stop();
        ui->lineEdit->setEnabled(true);
    }
}
//画图
void MainWindow::Chart_Init()
{
    isDraw=0;
    //初始化QChart的实例
    chart = new QChart();
    chart->setAnimationOptions(QChart::SeriesAnimations);
    //初始化QSplineSeries的实例
    lineSeries = new QSplineSeries();
    //设置曲线的名称
   lineSeries->setName("随机数测试曲线");
   chart->legend()->hide();
    //把曲线添加到QChart的实例chart中
    chart->addSeries(lineSeries);
    x=0;
    //初始化X轴、两个Y轴
    axisX = new QValueAxis();
    axisY = new QValueAxis();
    //设置坐标轴显示的范围
//    axisX->setMin(0);
//    axisX->setMax(MAX_X);
    axisX->setRange(x-1,x+1);
    axisY->setMin(0);
    axisY->setMax(MAX_Y);
    //设置坐标轴上的格点
    axisX->setTickCount(10);
    axisY->setTickCount(10);
    //设置坐标轴显示的名称
    QFont font("Microsoft YaHei",8,QFont::Normal);//微软雅黑。字体大小8
    axisX->setTitleFont(font);
    axisY->setTitleFont(font);
    axisX->setTitleText("X-Test");
    axisY->setTitleText("Y-Test");
    //设置网格显示
    axisY->setGridLineVisible(1);
    //下方：Qt::AlignBottom，左边：Qt::AlignLeft
    //右边：Qt::AlignRight，上方：Qt::AlignTop
    chart->addAxis(axisX, Qt::AlignBottom);
    chart->addAxis(axisY, Qt::AlignLeft);
    //把曲线关联到坐标轴
    lineSeries->attachAxis(axisX);
    lineSeries->attachAxis(axisY);
    //把chart显示到窗口上
    ui->chartView->setChart(chart);
    ui->chartView->setRenderHint(QPainter::Antialiasing);// 设置渲染：抗锯齿，如果不设置那么曲线就显得不平滑
    ui->chartView->setRubberBand(QChartView::RectangleRubberBand);
}

void MainWindow::drawsignal(){

};
void MainWindow::DrawLine()
{   if(isDraw){
    lineSeries->append(x+1, data.toInt());
    x+=0.1;
    // 更新X轴的范围
    axisX->setRange(x-1,x+1);
    //增加新的点到曲线末端
    //    lineSeries->append(x+1, rand()%65);//随机生成0到65的随机数
    }
}

//开始绘图按钮状态变化
void MainWindow::on_pushButton_6_clicked()
{
   isDraw=++isDraw%2;
   if(isDraw)
   {
    ui->pushButton_6->setText("停止绘图");
   }
   else{
    ui->pushButton_6->setText("开始绘图");
   }
}

//void MainWindow::zoom(QMouseEvent * event)
//{
//    //鼠标右键恢复初始化状态
//    if (event->button() == Qt::RightButton)
//    {
////        // 禁用缩放功能
////        ui->chartView->setRubberBand(QChartView::NoRubberBand);
//        //设置图表的缩放比例为1.0（即100%）来重置视图
////        ui->chartView->scale(1.0, 1.0);

//    }
//}
